package com.jp.single;
import com.jp.AbstractList;

public class SingleLinkedList <E> extends AbstractList<E> {

    private Node<E>first;

    private static class Node<E> {
        E element;
        Node<E> next;
        public Node(E element , Node<E>next) {
            this.element = element;
            this.next = next;
        }
        @Override
        public String toString() {
            StringBuilder string = new StringBuilder();

            string.append(element).append("_").append(next.element);

            return string.toString();
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = node(index);
        E oldElement = node.element;
        node.element = element;
        return oldElement;
    }

    @Override
    public void add(int index, E element) {
        
        rangeCheckForAdd(index);
        // 需要判断 添加的 第 0个位子
        if (index == 0) {
            first = new Node<E>(element, first);
        } else {
            Node<E> prev = node(index-1);
            prev.next = new Node<E>(element, prev.next);
        }
        size++;

    }

    @Override
    public E remove(int index) {

        rangeCheck(index);
        Node<E> node = first;
        // 判断 移除的是否为 第 0 个 位子
        if (index == 0) {
            first = first.next;
        } else {
            Node<E> prev = node(index-1);
            node = prev.next;
            prev.next = prev.next.next;
        }
        size--;
        return node.element;
    }

    @Override
    public int indexOf(E element) {
        if (element == null) {
            Node<E>node = first;
            for (int i = 0; i < size; i++) {
                if (node.element == null) return i;
                node = node.next;
            }
        } else {
            Node<E>node = first;
            for (int i = 0; i < size; i++) {
                if (node.element.equals(element)) return i;
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    private Node<E> node(int index) {
        rangeCheck(index);
        Node<E> node = first;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }
    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("size :").append(size).append("[");
        Node<E> node = first;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(node.element);
            node = node.next;
        }
        string.append("]");

        return string.toString();
    }

}